/**
 *  背景页面脚本
 */
define(function(require, exports, module) {
  "require:nomunge,exports:nomunge,module:nomunge";
  // 定义cache单个实例
  if ( window._cache === undefined ) {
    window._cache = {};

    //window._cache['siteUrl'] = 'http://wxscreen.sinaapp.com';
    window._cache['siteUrl'] = 'http://wxscreen.alltosun.net';
//    window._cache['siteUrl'] = 'http://wxscreen.com';
    window._cache['companyUrl'] = 'http://p.wxscreen.com';
    //window._cache['siteUrl'] = 'http://test45.wxscreen.com';

    window._cache['last_siteUrl']       = '';
    window._cache['server_proxyUrl']    = 'http://proxy.wxscreen.com';
    window._cache['server_proxyResult'] = null;
  };


  // 加载所有mpApi接口
  //-------------------------------------------

  //加载api函数库
  var api = require('/module/background/api.js');
  // 赋值到window属性
  window.mpApi = api;



  // 加载桌面通知模块
  //-------------------------------------------
  var notification = require('/module/background/notification.js');
  window.mpNotification = notification;


  // 消息通信（非port单条通信，有回调）
  //-------------------------------------------

  // 单条消息处理
  chrome.runtime.onMessage.addListener(function(msg, sender, responseFn){
    if ( !responseFn ) {
      return false;
    }
    if (msg.func) {
      api.messageHandler(msg, sender, responseFn);
    } else if(msg.api) {
      if (!wxqf_common[msg.api] || typeof wxqf_common[msg.api] != 'function') {
        responseFn({'error':'message.api is not a Funciton type'});
      } else {
        wxqf_common[msg.api](msg, sender, responseFn);
      }
    } else {
      responseFn({'error':'message.func is not a {Funciton} type'});
    }

    // must return true;
    return true;
  });


  // wxqfzs监听 =========================== start ==========================

  /**
   * 当要发送ajax时候设置头信息
   */
  chrome.webRequest.onBeforeSendHeaders.addListener(function(details){

    var tofakeid, token, headers = [];
    for(var i=0; i < details.requestHeaders.length; i++) {
      if (details.requestHeaders[i].name == 'wxqfzs_tofakeid') {
        tofakeid = details.requestHeaders[i].value;
      }
      if (details.requestHeaders[i].name == 'wxqfzs_token') {
        token = details.requestHeaders[i].value;
      }
      if (token && tofakeid) {
        break;
      }
    }
    // 设置Refer
    if(tofakeid && token) {
      var referer = wxqf_common.getPageUrl('singlesendpage', token);
      referer = referer.replace(/tofakeid\=\d+/, 'tofakeid='+tofakeid);
      for (var i =0; i < details.requestHeaders.length; i++) {
        if (details.requestHeaders[i].name == 'Referer') {
          details.requestHeaders[i].value = referer;
        }
        if (details.requestHeaders[i].name.indexOf('wxqfzs_') == -1) {
          headers.push(details.requestHeaders[i]);
        }
      }
    }

    if (!headers.length) headers = details.requestHeaders;
    if(wxqf_common.DEBUG) console.log('onBeforeSendHeaders', headers);

    return {requestHeaders: headers};


  }, {urls: ["https://mp.weixin.qq.com/cgi-bin/singlesend*"]}, ["blocking", "requestHeaders"]);

  /**
   * 恢复群发任务
   * @return {[type]} [description]
   */
  $(function(){
    //wxqf_task.unSerialize();
  });

  // wxqfzs监听 =========================== end ==========================




  // 通过port与页面通信
  //-------------------------------------------



  // 轮询消息总数
  //-------------------------------------------
  // 20131224移动到popup上

  // 定时检查坏死的任务
  // ------------------------------------------
  setInterval(function(){

    api.taskCheckRunning();

  }, 60*1000);

  // 定时储将任务数据存到本地
  // --------------------------------------------
  setInterval(function(){

    api.taskSerialize();

  }, 20*1000);

  // 定时监测服务器状态并自动切换
  /*setInterval(function(){
    api.pullServerState();
  }, 3*1000);*/

});